package pri.damai.xiaowu.auth.security.loginlogic.subClazz;

import cn.hutool.core.util.PhoneUtil;
import pri.damai.xiaowu.auth.security.loginlogic.LoginTypeEnums;
import pri.damai.xiaowu.auth.security.loginlogic.base.AbstractLoginLogic;
import pri.damai.xiaowu.auth.manager.SmsManager;
import pri.damai.xiaowu.auth.manager.UserManager;
import pri.damai.xiaowu.auth.security.model.LoginData;
import pri.damai.xiaowu.auth.security.model.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 手机号验证码登录
 * @Desc
 * @Author DaMai
 * @Date 2021/10/18 14:31
 * 但行好事，莫问前程。
 */
@Component
public class PhoneCodeLogin extends AbstractLoginLogic {

    @Resource
    SmsManager smsManager;
    @Resource
    UserManager userManager;

    @Override
    public LoginTypeEnums getSupportLoginType() {
        return LoginTypeEnums.PHONE_CODE;
    }

    @Override
    public void authenticateBefore(LoginData loginData) {

        ifTureThrowAuthException(
                StringUtils.isBlank(loginData.getPhone()) || !PhoneUtil.isPhone(loginData.getPhone()),
                "手机号格式错误。"
        );

        ifTureThrowAuthException(
                StringUtils.isBlank(loginData.getCode()),
                "验证码不可为空"
        );

    }

    @Override
    public UserInfo getUserDetails(LoginData loginData) {

        String code = smsManager.getLoginCode(loginData.getPhone());

        // todo 放开
//        // 验证码过期
//        ifTureThrowAuthException(
//                StringUtils.isBlank(code),
//                "验证码过期。"
//        );
//
//        // 验证码错误
//        ifTureThrowAuthException(
//                !Objects.equals(code, loginData.getCode()),
//                "验证码错误。"
//        );

        ifTureThrowAuthException(
                !Objects.equals(loginData.getCode(),"1234"),
                "验证码错误"
        );

        return userManager.getUserByPhone(loginData.getPhone());
    }

    @Override
    public void authenticateAfter(UserInfo userDetails) {
        // 删除验证码
        smsManager.deleteLoginCode(userDetails.getPhone());
    }
}
